<?php

namespace app\admin\controller;

use app\common\model\Admin;
use think\captcha\Captcha;
use think\Controller;
use think\Request;

class User extends Controller
{


    /**
     * @param Request $request
     *
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login(Request $request)
    {
        if (session('admin.id')) {
            $this->success('你已经登录', '/admin/index');
        }
        if ($request->isPost()) {
            $post = $request->post();
            $res = (new Admin())->login($post);
            if ($res) {
                $this->success($res['message'], '/admin/index');
            } else {
                $this->error($res['message']);
            }
        }
        return $this->fetch();
    }

    /**
     * 修改密码
     *
     * @param Request $request
     *
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public function password(Request $request)
    {
        if ($request->isPost()){
            $res=(new Admin())->change($request->param());
            if ($res){
                $this->success($res['message']);
            }else{
                $this->error($res['message']);
            }
        }
        $info = (new Admin())->getInfo();
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        session(null);
        $this->success('退出成功', 'user/login');
    }

    /**
     * 自定义验证码
     */
    public function captcha()
    {
        $config = [
            'codeSet' => '123456789',
            'length' => 2,
            'imageH' => 40,
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }
}
